<template lang="pug">
	.upload-id-photo-wrap
		.show-photo-wrap
			.title 请上传{{name}}的身份证头像面
			.tip 拍摄时请确保身份证边框完整、图像清晰、光线均匀
			canvas.head-canvas(id='headCanvas' canvas-id='headCanvas' :disable-scroll="true")
			.id-photo-wrap(@click="showCamera" v-if="idPhotoUrl.length<=0")
				.id-photo
					img(src="../../assets/image/faceAuthentication/cameraIcon.png")
					p 点击拍摄
			.id-photo-block(v-else :style="{'width':idPhotoHeight+'px','height':idPhotoWidth+'px'}")
				img(:src="idPhotoUrl" :style="{'width':idPhotoWidth+'px','height':idPhotoHeight+'px'}")
			.upload-btn(@click="next")
				main-button(text="下一步" :isActive="true")
			.photo-again(@click="showCamera" v-if="idPhotoUrl.length") 重新拍摄
		.take-photo-wrap(:animation="cameraAnimation")
			camera.camera(device-position="back" flash="auto" :binderror="openError")
				cover-view.cover-wrap
					cover-view.backdrop(ref="topBack")
					cover-view.cover-frame
						cover-view.backdrop(ref="leftBack")
						cover-view.cover-content
							cover-image.img(:src="coverImage" ref="head")
						cover-view.backdrop
					cover-view.backdrop
			.camera-tools
				.close(@click="back") 取消
				.btn(@click="takePhoto")
</template>

<script>
import coverImage from '@/assets/image/healthCard/header-camera.png'
import mainButton from '@/components/main-button'
export default {
	name: 'uploadIdPhoto',
	data() {
		return {
			cameraAnimation: '',
			coverImage: coverImage,
			clientHeight: '',
			clientWidth: '',
			rpxR: '',
			photoToken: '',
			name: '',
			idPhotoWidth: '', //拍摄后显示的身份证照片宽度
			idPhotoHeight: '', //拍摄后显示的身份证照片高度
			idPhotoUrl: '',
			idFaceBase64: ''
		}
	},
	created() {
		let that = this
		this.wx.getSystemInfo({
			success: function(res) {
				that.rpxR = 750 / res.windowWidth
				that.clientHeight = res.windowHeight
				that.clientWidth = res.windowWidth
			}
		})
	},
	mounted() {
		let that = this
		this.wx.getStorage({
			key: 'familyRole',
			success(res) {
				that.familyRole = res.data
				that.name = res.data.name
			}
		})
		this.animation = wx.createAnimation({
			duration: 300,
			timingFunction: 'ease'
		})
	},
	methods: {
		showCamera() {
			this.cameraAnimation = this.animation
				.translate3d(0, 0, 0)
				.step()
				.export()
		},
		back() {
			this.cameraAnimation = this.animation
				.translate3d(0, this.clientHeight, 0)
				.step()
				.export()
		},
		openError() {
			this.wx.showToast('不允许进行拍摄将无法进行人脸验证')
		},
		takePhoto() {
			const headCanvas = wx.createCanvasContext('headCanvas')
			const ctx = this.wx.createCameraContext()
			ctx.takePhoto({
				quality: 'high',
				success: res => {
					this.idPhotoUrl = res.tempImagePath
					this.wx.showLoading({
						title: '身份证识别中'
					})
					let photoWidth = this.clientWidth
					let photoHeight = this.clientHeight - 200 / this.rpxR
					this.idPhotoHeight = 684 / this.rpxR
					this.idPhotoWidth = this.idPhotoHeight * photoWidth / photoHeight
					let headTop = (photoHeight - 860 / this.rpxR) / 2 + 550 / this.rpxR //头像到照片顶部距离
					let dx =
						-1 * photoWidth / 2 +
						(photoHeight - photoWidth) / 2 +
						(photoWidth - 540 / this.rpxR) / 2 +
						98 / this.rpxR //照片左上角在目标 canvas 上 x 轴的位置
					let dy =
						-1 * photoHeight / 2 - headTop + (photoHeight - photoWidth) / 2 //照片左上角在目标 canvas 上 y 轴的位置
					headCanvas.translate(photoWidth / 2, photoHeight / 2) //移动到照片中心点
					headCanvas.rotate(-90 * Math.PI / 180)
					headCanvas.drawImage(res.tempImagePath, dx, dy)
					headCanvas.draw()
					setTimeout(() => {
						this.wx.canvasToTempFilePath({
							canvasId: 'headCanvas',
							success: res => {
								this.wx.getFileSystemManager().readFile({
									filePath: res.tempFilePath,
									encoding: 'base64',
									success: res => {
										this.idFaceBase64 = res.data
										this.faceDetection()
									}
								})
							},
							fail: res => {}
						})
					}, 800)
				},
				fail(res) {}
			})
		},
		async faceDetection() {
			await this.api.baiduApi
				.getAccessToken({
					grant_type: 'client_credentials',
					client_id: 'KGpj8RGpkLgtzCWn2NS3MEoq', //API Key
					client_secret: 'HR2GTZnA05bwZtwGMmg5OSNFFKZGG76L' //Secret Key
				})
				.then(data => {
					this.accessToken = data.access_token
				})
				.catch(err => {})
			this.api.baiduApi
				.faceDetection({
					image_type: 'BASE64',
					image: this.idFaceBase64,
					access_token: this.accessToken
				})
				.then(data => {
					this.wx.hideLoading()
					if (
						data.error_code === 0 &&
						data.result.face_num === 1 &&
						data.result.face_list[0].face_probability > 0.8
					) {
						this.back()
						Obeject.assign(this.familyRole, { idFaceBase64: this.idFaceBase64 })
						this.wx.setStorage({
							key: 'familyRole',
							data: this.familyRole
						})
					} else {
						this.wx.showToast({
							title: '照片不符合要求，请重新拍摄哦',
							icon: 'none'
						})
					}
				})
				.catch(err => {})
		},
		next() {
			if (this.idFaceBase64.length > 0) {
				this.$router.push({
					path: '/views/faceAuthentication/faceDetection',
					query: {
						mode: 'twoFace'
					}
				})
			}
		}
	},
	components: {
		mainButton
	}
}
</script>

<style lang="stylus">
	.upload-id-photo-wrap
		.show-photo-wrap
			text-align center
			.head-canvas
				width 270px
				height 302px
				position fixed
				top 0
				left 0
				opacity 0
				pointer-events none
			.title
				font-size 28px
				color blackFontColor1A
				line-height 40px
				padding 40px 0 0
			.tip
				font-size 24px
				color grayFontColor88
				line-height 34px
				padding 20px 0 40px
			.id-photo-wrap
				width 714px
				height 384px
				centerBackground('../../assets/image/faceAuthentication/idPhotoBg.png')
				center()
				margin 0 auto
				img
					width 100px
					height 84px
				p
					font-size 30px
					font-weight 600px
					color #666
					padding 10px 0 0 0
			.id-photo-block
				margin 0 auto
				position relative
				img
					display block
					position absolute
					top 50%
					left 50%
					transform translate3d(-50%,-50%,0) rotate(-90deg)
			.upload-btn
				width 690px
				height 92px
				margin 60px auto 0
				border-radius 46px
				overflow hidden
			.photo-again
				margin-top 30px
				text-align center
				font-size 26px
				line-height 36px
				font-weight 400
				color themeColor
		.take-photo-wrap
			position fixed
			cover()
			transform translate3d(0,100%,0)
			.camera
				position absolute
				cover()
				bottom 200px
				.backdrop
					background-color rgba(0,0,0,0.6)
					flex 1
				.cover-wrap
					position relative
					height 100%
					display flex
					flex-direction column
					.cover-frame
						height 860px
						display flex
					.cover-content
						width 540px
						height 100%
						position relative
						.img
							width 302px
							height 270px
							position absolute
							top 550px
							right 98px
			.camera-tools
				height 200px
				width 100%
				position absolute
				bottom 0
				background-color black
				center()
				.close
					position absolute
					left 0
					width 200px
					height 100%
					center()
					font-size 34px
					color white
				.btn
					width 120px
					height 120px
					background-color white
					center()
					border-radius 50%
					&::after
						border-radius 50%
						content ''
						width 75%
						height 75%
						display block
						border 4px solid black

</style>
